785. 判断二分图
为保证权益,题目请参考 785. 判断二分图(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution
{
vector<int> status;
vector<vector<int>> *graph;
bool isBad = false;
public:
bool isBipartite(vector<vector<int>> &graph)
{
this->graph = &graph;
status.assign(graph.size(), 0);
status[0] = 1;
dfs(0);
return !isBad;
}
void dfs(int i)
{
if (isBad)
{
return;
}
for (int j = 0; j < graph[i].size(); j++)
{
int tar = graph[i][j];
if (status[j] == 0)
{
status[j] = -status[i];
dfs(j);
}
else if (status[j] == status[i])
{
isBad = true;
return;
}
}
}
};
int main()
{
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48